<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">发起拼团</block>
		</cu-custom>
		<view class="cu-card article" v-if="grouponInfo.goodsSku">
			<view class="cu-item padding-top">
				<navigator v-if="theme.showType!=2" class="padding-lr padding-bottom" hover-class="none" :url="'/pages/shop/shop-detail/index?id=' + grouponInfo.shopInfo.id">
					<view class="cu-avatar sm radius " :style="'background-image:url(' + grouponInfo.shopInfo.imgUrl + ')'"></view>
					<text class="text-black text-bold margin-left-sm">{{grouponInfo.shopInfo.name}}</text>
					<text class="text-sm"></text>
				</navigator>
				<view style="margin-top: -10rpx;">
					<view class="action margin-left text-df">
						<text class="cuIcon-hotfill  margin-right-xs" :class="'text-'+theme.themeColor"></text>{{grouponInfo.name}}
					</view>
					<view style="margin:10rpx 0 10rpx 30rpx;">
						<text class="cu-tag line-orange radius margin-right-sm">{{grouponInfo.grouponNum}}人团</text>
						<text class="text-sm text-grey" v-if="grouponInfo.launchNum">已有{{grouponInfo.launchNum}}人参与</text>
						<text class="text-blue text-sm margin-left" style="margin-left: 280rpx;" @tap="ruleShow">拼团规则</text>
					</view>
				</view>
				<view class="content">
					<image :src="grouponInfo.picUrl" mode="aspectFill" class="row-img margin-top-xs"></image>
					<view class="desc block">
						<view class="text-black margin-top-sm overflow-2">{{grouponInfo.goodsSpu.name}}</view>
						<view class="text-gray text-sm " v-if="grouponInfo.goodsSku&&grouponInfo.goodsSku.specs&&grouponInfo.goodsSku.specs.length > 0">{{specInfo}}</view>
						<view class="flex justify-start margin-top-sm align-center">
							<view class="text-price text-bold text-xl text-red">{{grouponInfo.grouponPrice}}</view>
							<view class="text-price text-decorat text-gray margin-left-sm">{{grouponInfo.goodsSku.salesPrice}}</view>
							<view class="cu-tag bg-red radius sm margin-left" v-if="grouponInfo.goodsSpu.freightTemplat.type == '2'">包邮</view>
						</view>
					</view>
				</view>
				<view class="margin-top text-center">
					<button class="cu-btn share round bg-green shadow-blur" @tap="shareShowFun">
						<text class="cuIcon-share">分享</text>
					</button>
				</view>
				<view class="text-gray text-sm margin-top text-center" v-if="grouponInfo.validBeginTime">{{grouponInfo.validBeginTime}}至{{grouponInfo.validEndTime}}</view>
			</view>
		</view>

		<view class="cu-card mar-top-30" v-if="grouponUserList.length > 0">
			<view class="cu-item">
				<view class="cu-bar bg-white solid-bottom">
					<view class="action">
						<text class="cuIcon-titles" :class="'text-'+theme.themeColor"></text>已有{{grouponUserTotal}}个拼单，可直接参与</view>
				</view>
				<view class="cu-list menu-avatar padding-right-xs">
					<view class="cu-item" v-for="(item, index) in grouponUserList" :key="index">
						<view class="cu-avatar round lg" :style="'background-image:url(' + item.headimgUrl + ');'"></view>
						<view class="content">
							<view class="flex">
								<view class="flex-sub">{{item.nickName}}</view>
								<view class="flex-twice text-right text-sm">
									<count-down class="text-red" :outTime="dateUtil.getOutTime(item.validEndTime)" @countDownDone="countDownDone"></count-down>
									<view>还差<text class="text-red">{{item.grouponNum - item.havgrouponNum}}人</text>拼成</view>
								</view>
							</view>
						</view>
						<view class="action">
							<navigator class="cu-btn sm round" :class="'bg-'+theme.themeColor" hover-class="none" :url="'/pages/groupon/groupon-user-detail/index?id=' + item.id">去拼单</navigator>
						</view>
					</view>
					<view class="cu-load bg-white" v-if="loadmore" @tap="loadMore">加载更多</view>
				</view>
			</view>
		</view>

		<view class="cu-card mar-top-30">
			<view class="cu-item">
				<view class="cu-bar bg-white">
					<view class="content">商品信息</view>
				</view>
				<view class="bg-white">
					<jyf-parser :html="article_description"></jyf-parser>
				</view>
				<view class="cu-load bg-gray to-down">已经到底啦...</view>
			</view>
		</view>
		<!-- html转wxml -->
		<view class="cu-bar bg-white tabbar border shop foot" v-if="grouponInfo.goodsSku">
			<navigator class="action bg-white" open-type="navigate"
				:url="'/pages/customer-service/customer-service-list/index?shopId='+grouponInfo.shopId">
				<view class="cuIcon-servicefill"></view>客服
			</navigator>
			<view class="bg-orange submit" @tap="tobuy">
				<view class="grid col-1 text-center">
					<view class="text-price">{{grouponInfo.goodsSku.salesPrice}}</view>
					<view>原价购买</view>
				</view>
			</view>
			<view :class="'bg-' + (grouponInfo.status == '1' && grouponInfo.enable == '1' ? 'blue' : 'gray') + ' submit'" @tap="toGroupon">
				<view class="grid col-1 text-center">
					<view class="text-price">{{grouponInfo.grouponPrice}}</view>
					<view>{{grouponInfo.enable == '0' ? '拼团已关闭' :grouponInfo.status == '0' ? '拼团未开始' : grouponInfo.status == '1' ? '发起拼团' : grouponInfo.status == '2' ? '拼团已过期' : ''}}</view>
				</view>
			</view>
		</view>

		<view :class="'cu-modal ' + modalRule">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">规则说明</view>
					<view class="action" @tap="ruleHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<text>{{grouponInfo.grouponRule}}</text>
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + (grouponInfo.goodsSpu.shelf=='0'||!grouponInfo.goodsSku  ? 'show' : '')">
			<view class="cu-dialog bg-white">
				<view class="cu-bar  justify-end">
					<view class="content">提示</view>
				</view>
				<view class="padding-xl">
					抱歉，该商品已下架
				</view>
				<view class="padding">
					<navigator open-type="navigateBack" class="cu-btn margin-top response lg" :class="'bg-'+theme.themeColor">
						确定
					</navigator>
				</view>
			</view>
		</view>

		<!-- 分享组件 -->
		<share-component v-model="showShare" :shareParams="shareParams"></share-component>

	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	import shopInfo from "components/shop-info/index";

	const util = require("utils/util.js");
	const {
		base64src
	} = require("utils/base64src.js");
	const app = getApp();
	import api from 'utils/api'
	import dateUtil from 'utils/dateUtil'
	import jweixin from 'utils/jweixin'

	import countDown from "components/count-down/index";
	import shareComponent from "@/components/share-component/index"

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				dateUtil:dateUtil,
				grouponInfo: {
					goodsSku:{},
					goodsSpu:{
						freightTemplat: {}
					},
					shopInfo:{},
					grouponNum: 0
				},
				disabled: false,
				page: {
					searchCount: true,
					current: 1,
					size: 5,
					ascs: '',
					//升序字段
					descs: 'create_time'
				},
				parameter: {},
				grouponUserList: [],
				grouponUserTotal: 0,
				loadmore: true,
				shareShow: '',
				curLocalUrl: '',
				userInfo: null,
				modalRule: '',
				id: "",
				specInfo: "",
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				article_description: "",
				showShare: false,
				shareParams: {}
			};
		},

		components: {
			shareComponent,
			countDown,
		},
		props: {},

		onShow() {
			app.initPage().then(res => {
				this.grouponInfoGet();
				this.grouponUserList = [];
				this.grouponUserPageGrouponing();
			});
		},

		onLoad(options) {
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			// this.dateUtil = dateUtil;
			let id;

			if (options.scene) {
				//接受二维码中参数
				let scenes = decodeURIComponent(options.scene).split('&');
				id = scenes[0];
			} else {
				id = options.id;
			}

			this.id = id;
			this.userInfo = uni.getStorageSync('user_info');
		},

		onShareAppMessage: function() {
			let grouponInfo = this.grouponInfo;
			let title = grouponInfo.shareTitle;
			let imageUrl = grouponInfo.picUrl;
			let path = '';
			path = 'pages/groupon/groupon-detail/index?id=' + grouponInfo.id;

			const userInfo = uni.getStorageSync('user_info')
			const userCode = userInfo ? '&sharer_user_code='+userInfo.userCode : ''

			path = path +  userCode;
			return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			//查询拼团信息
			grouponInfoGet() {
				api.grouponInfoGet(this.id).then(res => {
					let grouponInfo = res.data;
					let goodsSku = grouponInfo.goodsSku;
					let specInfo = '';
					if(goodsSku&&goodsSku.specs)
					goodsSku.specs.forEach(function(specItem, index) {
						specInfo = specInfo + specItem.specValueName;

						if (goodsSku.specs.length != index + 1) {
							specInfo = specInfo + ';';
						}
					});
					this.grouponInfo = grouponInfo;
					this.specInfo = specInfo;
					this.article_description = grouponInfo.goodsSpu?grouponInfo.goodsSpu.description:'';
				});
			},

			//拼团中记录列表
			grouponUserPageGrouponing() {
				api.grouponUserPageGrouponing(Object.assign({
					grouponId: this.id,
					isLeader: '1',
					status: '0'
				}, this.page, util.filterForm(this.parameter))).then(res => {
					let grouponUserList = res.data.records;
					this.grouponUserList = [...this.grouponUserList, ...grouponUserList];
					this.grouponUserTotal = res.data.total;
					if (grouponUserList.length < this.page.size) {
						this.loadmore = false;
					}
				});
			},

			//原价购买
			tobuy() {
				let grouponInfo = this.grouponInfo;
				let goodsSpu = grouponInfo.goodsSpu;
				let goodsSku = grouponInfo.goodsSku;
				let specInfo = this.specInfo;
				/* 把参数信息异步存储到缓存当中 */

				uni.setStorage({
					key: 'param-orderConfirm',
					data: [{
						spuId: goodsSpu.id,
						skuId: goodsSku.id,
						quantity: 1,
						salesPrice: goodsSku.salesPrice,
						spuName: goodsSpu.name,
						specInfo: specInfo,
						picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
						pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
						pointsDeductScale: goodsSpu.pointsDeductScale,
						pointsDeductAmount: goodsSpu.pointsDeductAmount,
						pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
						pointsGiveNum: goodsSpu.pointsGiveNum,
						freightTemplat: goodsSpu.freightTemplat,
						weight: goodsSku.weight,
						volume: goodsSku.volume,
						shopInfo: grouponInfo.shopInfo
					}]
				});
				uni.navigateTo({
					url: '/pages/order/order-confirm/index'
				});
			},

			//发起拼团
			toGroupon(e) {
				let grouponInfo = this.grouponInfo;
				if (grouponInfo.status != '1') {
					uni.showToast({
						title: '暂时无法发起拼团！',
						icon: 'none'
					})
					return;
				}
				if(grouponInfo.enable == '0'){
					uni.showToast({
						title: '该拼团已关闭！',
						icon: 'none'
					})
					return;
				}
				let goodsSpu = grouponInfo.goodsSpu;
				let goodsSku = grouponInfo.goodsSku;

				if (goodsSku.stock > 0) {
					/* 把参数信息异步存储到缓存当中 */
					uni.setStorage({
						key: 'param-orderConfirm',
						data: [{
							spuId: goodsSpu.id,
							skuId: goodsSku.id,
							quantity: 1,
							salesPrice: grouponInfo.grouponPrice,
							spuName: goodsSpu.name,
							specInfo: this.specInfo,
							picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
							freightTemplat: goodsSpu.freightTemplat,
							weight: goodsSku.weight,
							volume: goodsSku.volume,
							orderType: '2',
							marketId: grouponInfo.id,
							shopInfo: grouponInfo.shopInfo
						}]
					});
					uni.navigateTo({
						url: '/pages/groupon/groupon-order-confirm/index'
					});
				} else {
					uni.showToast({
						title: '拼团商品库存不足',
						icon: 'none',
						duration: 2000
					});
				}
			},

			shareShowFun() {
				let desc = '长按识别小程序码';
				let shareImg = this.grouponInfo.picUrl;
				// #ifdef H5 || APP-PLUS
					desc = '长按识别二维码';
					// h5的海报分享的图片有的有跨域问题，所以统一转成base64的
					// 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
					shareImg = util.imgUrlToBase64(shareImg);
				// #endif
					//海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
					let posterConfig = {
						width: 750,
						height: 1280,
						backgroundColor: '#fff',
						debug: false,
						blocks: [{
							width: 690,
							height: 808,
							x: 30,
							y: 183,
							borderWidth: 2,
							borderColor: '#f0c2a0',
							borderRadius: 20
						}, {
							width: 634,
							height: 74,
							x: 59,
							y: 770,
							backgroundColor: '#fff',
							opacity: 0.5,
							zIndex: 100
						}],
						texts: [{
							x: 30,
							y: 113,
							baseLine: 'top',
							text: this.grouponInfo.shareTitle,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 92,
							y: 810,
							fontSize: 38,
							baseLine: 'middle',
							text: this.grouponInfo.goodsSpu.name,
							width: 570,
							lineNum: 1,
							color: '#080808',
							zIndex: 200
						}, {
							x: 59,
							y: 895,
							baseLine: 'middle',
							text: [{
								text: '拼团价',
								fontSize: 28,
								color: '#ec1731'
							}, {
								text: '¥' + this.grouponInfo.grouponPrice,
								fontSize: 36,
								color: '#ec1731',
								marginLeft: 30
							}]
						}, {
							x: 522,
							y: 895,
							baseLine: 'middle',
							text: '原价 ¥' + this.grouponInfo.goodsSku.salesPrice,
							fontSize: 28,
							color: '#929292'
						}, {
							x: 59,
							y: 945,
							baseLine: 'middle',
							text: [{
								text: this.grouponInfo.goodsSpu.sellPoint,
								fontSize: 28,
								color: '#929292',
								width: 570,
								lineNum: 1
							}]
						}, {
							x: 360,
							y: 1065,
							baseLine: 'top',
							text: desc,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 360,
							y: 1123,
							baseLine: 'top',
							text: '快来和我一起拼一单吧！',
							fontSize: 28,
							color: '#929292'
						}],
						images: [{
							width: 634,
							height: 634,
							x: 59,
							y: 210,
							url: shareImg
						}, {
							width: 230,
							height: 230,
							x: 92,
							y: 1020,
							url: null,
							qrCodeName: 'qrCodeName',// 二维码唯一区分标识
						}]
					};
					let userInfo = uni.getStorageSync('user_info');

					if (userInfo && userInfo.headimgUrl) {
						//如果有头像则显示
						posterConfig.images.push({
							width: 62,
							height: 62,
							x: 30,
							y: 30,
							borderRadius: 62,
							url: userInfo.headimgUrl
						});
						posterConfig.texts.push({
							x: 113,
							y: 61,
							baseLine: 'middle',
							text: userInfo.nickName,
							fontSize: 32,
							color: '#8d8d8d'
						});
					}


				this.shareParams = {
					title:  this.grouponInfo.shareTitle,
					desc: this.grouponInfo.goodsSpu.name,
					imgUrl: this.grouponInfo.picUrl,
					scene: this.grouponInfo.id,
					page: 'pages/groupon/groupon-detail/index',
					posterConfig: posterConfig
				}
				this.showShare = true;
			},

			ruleShow() {
				this.modalRule = 'show';
			},
			ruleHide() {
				this.modalRule = '';
			},
			countDownDone() {
				this.onLoad();
			}
		}
	};
</script>
<style>
	.row-img {
		width: 200rpx !important;
		height: 200rpx !important;
		border-radius: 10rpx
	}

	.cu-bar.tabbar.shop .action {
		width: unset;
	}

	.to-down {
		margin-top: 120rpx;
	}

	.share{
		width: 580rpx;
		height: 76rpx;
	}

	.show-bg{
		height: 84%;
		margin-top: 120rpx;
	}

	.image-box{
		height: 90%;
	}

	.show-btn{
		margin-top: -130rpx;
	}
</style>
